--函数！

--用法：local HX = require "packages.hx_gamemode.hxfs"
--如HX.DrawCardFromPile(player.room, player, baguan2022.name, 2)

local hxfs = {}

--- 从已经开启的拓展包中，随机选出若干名武将。
---
--- 同名武将不会重复选取，武将数量也会返回能找到的武将
---@param num integer @ 要选出的武将数量
---@param generalPool? string[] @ 选择的范围，默认是已经启用的所有武将的武将名
---@param except? string[] @ 特别要排除掉的武将名列表，默认是空表
---@param filter? fun(g: General): boolean? @ 可选参数，若这个函数返回true的话这个武将被排除在外
---@return General[] @ 随机选出的武将列表
function hxfs.getGenerals(num, generalPool, except, filter)
  if filter then
    assert(type(filter) == "function")
  end

  generalPool = generalPool or table.map(Fk:getAllGenerals(), Util.NameMapper)
  except = except or {}
  except = table.simpleClone(except)
  for _, g in ipairs(Fk.packages["test_p_0"].generals) do
    table.insert(except, g.name)
  end

  local availableGenerals = {}
  for _, gn in pairs(generalPool) do
    local general = Fk.generals[gn]
    if not table.contains(except, general.name) and not (filter and filter(general)) then
      if (not general.hidden and not general.total_hidden) and
          #table.filter(availableGenerals, function(g)
            return g.trueName == general.trueName
          end) == 0 then
        table.insert(availableGenerals, general)
      end
    end
  end
  return table.random(availableGenerals, num)
end

--获取玩家的特别关注武将
---@param room Room @ 房间
---@param players ServerPlayer[] @ 玩家们
---@param ignorewhite boolean @ 无视禁将,默认不无视
---@return table <integer, string[]> > @ 玩家特别关注武将，返回键值表
hxfs.getPlayerStarGenerals = function(room, players, ignorewhite)
  local ret = {}
  local req = Request:new(players, "CustomDialog")
  ignorewhite = ignorewhite or false
  local d = {
    path = "packages/hx_gamemode/qml/GetStarGeneral.qml",
    data = {
      players[1].id
    },
  }
  local default = { "liubei" }
  for _, p in ipairs(players) do
    req:setData(p, d)
    req:setDefaultReply(p, default)
  end
  for _, p in ipairs(players) do
    local result = req:getResult(p)
    ret[tostring(p.id)] = {}
    if ignorewhite then
      ret[tostring(p.id)] = result
    else
      local satr = {}
      for _, g in ipairs(result) do
        if table.contains(room.general_pile, g) then
          table.insertIfNeed(satr, g)
        end
      end
      ret[tostring(p.id)] = satr
    end
  end
  return ret
end

return hxfs
